package com.hits.buildqrcode.config;

import com.hits.buildqrcode.domian.IpPort;
import com.hits.buildqrcode.util.SpringUtil;
import com.hits.buildqrcode.utils.OkHttpUtils;
import okhttp3.*;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @Author ly
 * @Date 2021/6/8 10:27
 * @Version 1.0
 */
@Component
public class HttpClient {

    private static OkHttpClient okHttpClient = OkHttpUtils.getInstance();

    public static String getTokenToInterFace(String data) throws IOException {
        MediaType JSON = MediaType.parse("application/json;charset=utf-8");
        RequestBody requestBody = RequestBody.create(JSON, data);
        IpPort ipPort = SpringUtil.getBean(IpPort.class);
        Request request = new Request.Builder()
                .url("http://"+ipPort.getIp()+":"+ipPort.getPort()+"/sfjdsj_ws/api/getToken")
                .post(requestBody)
                .build();
        okHttpClient.newBuilder().connectTimeout(60000, TimeUnit.MILLISECONDS)
                .readTimeout(60000,TimeUnit.MILLISECONDS).build();

        try (Response response = okHttpClient.newCall(request).execute()) {
            if (response.isSuccessful()) {
                return response.body().string();
            } else {
                throw new IOException("Unexpected code " + response);
            }
        }
    }

    public static String getCodeToInterFace(String data) throws IOException {
        MediaType JSON = MediaType.parse("application/json;charset=utf-8");
        RequestBody requestBody = RequestBody.create(JSON, data);
        IpPort ipPort = SpringUtil.getBean(IpPort.class);
        Request request = new Request.Builder()
                .url("http://"+ipPort.getIp()+":"+ipPort.getPort()+"/sfjdsj_ws/api/createCaseQRCode")
                .post(requestBody)
                .build();
        okHttpClient.newBuilder().connectTimeout(60000, TimeUnit.MILLISECONDS)
                .readTimeout(60000,TimeUnit.MILLISECONDS).build();

        try (Response response = okHttpClient.newCall(request).execute()) {
            if (response.isSuccessful()) {
                return response.body().string();
            } else {
                throw new IOException("Unexpected code " + response);
            }
        }
    }
}
